#pragma once
#include <iostream>
#include <string>
#include <pthread.h>
#include <unistd.h>
#include <functional>

namespace mythread
{
    static int count = 0;
    enum class TSTATUS
    {
        NEW,
        RUNNING,
        STOPPED
    };
    template <typename T>
    class thread
    {

        static void *Routine(void *arg)
        {
            thread *t = static_cast<thread *>(arg);
            t->_func(t->_data);
            t->_status = TSTATUS::RUNNING;
            return nullptr;
        }
        
        void detachenjion()
        {
            _enjoinable = false;
        }
    public:
        using func_t = std::function<void(T)>;
        thread(func_t func,T data) 
        : _func(func) ,_data(data),_enjoinable(true), _status(TSTATUS::NEW)
        {
            _name = "thread" + std::to_string(count++);
            _pid = getpid();
        }
        bool start()
        {
            if (TSTATUS::RUNNING != _status)
            {
                int n = pthread_create(&_tid, nullptr, Routine, this);
                if (n != 0)
                {
                    std::cerr << "pthread_create failed" << std::endl;
                    return false;
                }
                _status = TSTATUS::RUNNING;
                return true;
            }
            return false;
        }
        bool join()
        {
            if(_enjoinable)
            {
                int n = pthread_join(_tid, nullptr);
                if (n != 0)
                {
                    std::cerr << "pthread_join failed" << std::endl;
                    return false;
                }
                _status = TSTATUS::STOPPED;
                return true;
            }
            return false;
        }
        bool detach()
        {
            if(_enjoinable)
            {
                int n = pthread_detach(_tid);
                if (n != 0)
                {
                    std::cerr << "pthread_detach failed" << std::endl;
                    return false;
                }
                _enjoinable = false;
                return true;
            }
        }
        
        bool isjoinable()
        {
            return _enjoinable;
        }
        std::string name() const { return _name; }
        ~thread() { std::cout << "thread::~thread()" << std::endl; }

    private:
        std::string _name;
        pthread_t _tid;
        bool _enjoinable;
        pid_t _pid;
        TSTATUS _status;
        T _data;
        func_t _func;
    };

} // namespace mythread
